#!/usr/bin/env python3
"""
数据库初始化脚本
用于初始化数据库表结构和基础数据
"""

import asyncio
import os
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlmodel import SQLModel, select
from database.models import User, Category, SystemConfig, UserRole
from database.connection import DATABASE_URL
import bcrypt


async def create_admin_user(session: AsyncSession):
    """创建默认管理员用户"""
    # 检查是否已存在管理员用户
    result = await session.execute(select(User).where(User.username == "admin"))
    existing_admin = result.scalar_one_or_none()
    
    if existing_admin:
        print("管理员用户已存在，跳过创建")
        return
    
    # 创建管理员用户
    hashed_password = bcrypt.hashpw("admin123".encode('utf-8'), bcrypt.gensalt())
    admin_user = User(
        email="admin@example.com",
        username="admin",
        hashed_password=hashed_password.decode('utf-8'),
        full_name="系统管理员",
        role=UserRole.ADMIN,
        is_active=True
    )
    
    session.add(admin_user)
    await session.commit()
    print("管理员用户创建成功")


async def create_default_categories(session: AsyncSession):
    """创建默认商品分类"""
    # 检查是否已存在分类
    result = await session.execute(select(Category))
    existing_categories = result.scalars().all()
    
    if existing_categories:
        print("商品分类已存在，跳过创建")
        return
    
    # 默认分类数据
    default_categories = [
        Category(name="钥匙扣", description="个性化钥匙扣定制", sort_order=1),
        Category(name="手机支架", description="创意手机支架", sort_order=2),
        Category(name="摆件", description="装饰性摆件", sort_order=3),
        Category(name="玩具", description="创意玩具", sort_order=4),
        Category(name="日用品", description="实用日用品", sort_order=5),
        Category(name="礼品", description="定制礼品", sort_order=6),
    ]
    
    for category in default_categories:
        session.add(category)
    
    await session.commit()
    print("默认商品分类创建成功")


async def create_system_configs(session: AsyncSession):
    """创建系统配置"""
    # 检查是否已存在配置
    result = await session.execute(select(SystemConfig))
    existing_configs = result.scalars().all()
    
    if existing_configs:
        print("系统配置已存在，跳过创建")
        return
    
    # 默认系统配置
    default_configs = [
        SystemConfig(
            config_key="site_name",
            config_value="3D定制商品生产平台",
            description="网站名称",
            config_type="string"
        ),
        SystemConfig(
            config_key="site_description",
            config_value="专业的3D定制商品生产平台",
            description="网站描述",
            config_type="string"
        ),
        SystemConfig(
            config_key="max_file_upload_size",
            config_value="10485760",
            description="最大文件上传大小（字节）",
            config_type="integer"
        ),
        SystemConfig(
            config_key="allowed_image_formats",
            config_value='["jpg", "jpeg", "png", "gif", "webp"]',
            description="允许的图片格式",
            config_type="json"
        ),
        SystemConfig(
            config_key="allowed_3d_formats",
            config_value='["glb", "gltf", "obj", "stl", "fbx", "dae"]',
            description="允许的3D模型格式",
            config_type="json"
        ),
        SystemConfig(
            config_key="production_lead_time_days",
            config_value="7",
            description="默认生产周期（天）",
            config_type="integer"
        ),
        SystemConfig(
            config_key="shipping_fee_base",
            config_value="10.00",
            description="基础运费",
            config_type="float"
        ),
        SystemConfig(
            config_key="order_auto_cancel_hours",
            config_value="24",
            description="订单自动取消时间（小时）",
            config_type="integer"
        ),
        SystemConfig(
            config_key="enable_shopify_sync",
            config_value="false",
            description="是否启用Shopify同步",
            config_type="boolean"
        ),
        SystemConfig(
            config_key="enable_email_notifications",
            config_value="true",
            description="是否启用邮件通知",
            config_type="boolean"
        ),
    ]
    
    for config in default_configs:
        session.add(config)
    
    await session.commit()
    print("系统配置创建成功")


async def init_database():
    """初始化数据库"""
    print("开始初始化数据库...")
    
    # 创建数据库引擎
    engine = create_async_engine(DATABASE_URL, echo=True)
    
    # 创建会话
    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    
    async with async_session() as session:
        try:
            # 创建所有表
            print("创建数据库表...")
            async with engine.begin() as conn:
                await conn.run_sync(SQLModel.metadata.create_all)
            print("数据库表创建完成")
            
            # 创建默认数据
            await create_admin_user(session)
            await create_default_categories(session)
            await create_system_configs(session)
            
            print("数据库初始化完成！")
            
        except Exception as e:
            print(f"数据库初始化失败: {e}")
            await session.rollback()
            raise
        finally:
            await session.close()
    
    await engine.dispose()


if __name__ == "__main__":
    print("3D定制商品生产平台 - 数据库初始化脚本")
    print("=" * 50)
    
    # 运行异步初始化
    asyncio.run(init_database())
    
    print("\n初始化完成！")
    print("默认管理员账号: admin / admin123")
    print("请尽快修改默认密码以确保安全！")